import React, { createContext, useState, useContext, useEffect } from 'react';
import { ColorSchemeName, useColorScheme as _useColorScheme } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 定义字体大小类型
export type FontSize = 'small' | 'medium' | 'large';

// 定义主题上下文类型
type ThemeContextType = {
  colorScheme: ColorSchemeName;
  setColorScheme: (scheme: ColorSchemeName) => void;
  fontSize: FontSize;
  setFontSize: (size: FontSize) => void;
  toggleColorScheme: () => void;
};

// 创建主题上下文
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// 定义主题提供者组件
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  // 获取系统颜色方案
  const systemColorScheme = _useColorScheme();
  
  // 状态管理
  const [colorScheme, setColorScheme] = useState<ColorSchemeName>(systemColorScheme);
  const [fontSize, setFontSize] = useState<FontSize>('medium');

  // 初始化时从存储中加载设置
  useEffect(() => {
    const loadSettings = async () => {
      try {
        // 加载颜色方案设置
        const savedColorScheme = await AsyncStorage.getItem('colorScheme');
        if (savedColorScheme) {
          setColorScheme(savedColorScheme as ColorSchemeName);
        }
        
        // 加载字体大小设置
        const savedFontSize = await AsyncStorage.getItem('fontSize');
        if (savedFontSize) {
          setFontSize(savedFontSize as FontSize);
        }
      } catch (error) {
        console.error('加载设置失败:', error);
      }
    };
    
    loadSettings();
  }, []);

  // 保存颜色方案设置
  const handleSetColorScheme = async (scheme: ColorSchemeName) => {
    try {
      await AsyncStorage.setItem('colorScheme', scheme as string);
      setColorScheme(scheme);
    } catch (error) {
      console.error('保存颜色方案设置失败:', error);
    }
  };

  // 保存字体大小设置
  const handleSetFontSize = async (size: FontSize) => {
    try {
      await AsyncStorage.setItem('fontSize', size);
      setFontSize(size);
    } catch (error) {
      console.error('保存字体大小设置失败:', error);
    }
  };

  // 切换颜色方案
  const toggleColorScheme = () => {
    const newScheme = colorScheme === 'dark' ? 'light' : 'dark';
    handleSetColorScheme(newScheme);
  };

  return (
    <ThemeContext.Provider
      value={{
        colorScheme,
        setColorScheme: handleSetColorScheme,
        fontSize,
        setFontSize: handleSetFontSize,
        toggleColorScheme,
      }}
    >
      {children}
    </ThemeContext.Provider>
  );
};

// 自定义hook，用于在组件中访问主题上下文
export const useTheme = (): ThemeContextType => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

// 自定义hook，用于获取当前颜色方案
export const useColorScheme = (): ColorSchemeName => {
  const { colorScheme } = useTheme();
  return colorScheme;
};